package com.silence.gankio.sp

import android.content.Context
import android.content.SharedPreferences
import com.silence.gankio.core.app.Core


open class SPUtil protected constructor(spName: String) {

    protected val SP_NAME = "config"
    protected val mSharePre: SharedPreferences = Core.getApplication().getSharedPreferences(spName, Context.MODE_PRIVATE)


    /* get and put String value */
    fun setValue(key: String, value: String) {
        mSharePre.edit().putString(key, value).apply()
    }

    fun getValue(key: String, defValue: String): String? {
        return mSharePre.getString(key, defValue)
    }

    /* get and put boolean value */
    fun setValue(key: String, value: Boolean) {
        mSharePre.edit().putBoolean(key, value).apply()
    }

    fun getValue(key: String, defValue: Boolean): Boolean {
        return mSharePre.getBoolean(key, defValue)
    }

    /* get and put int value */
    fun setValue(key: String, value: Int) {
        mSharePre.edit().putInt(key, value).apply()
    }

    fun getValue(key: String, defValue: Int): Int {
        return mSharePre.getInt(key, defValue)
    }

    /* get and put int value */
    fun setValue(key: String, value: Float) {
        mSharePre.edit().putFloat(key, value).apply()
    }

    fun getValue(key: String, defValue: Float): Float {
        return mSharePre.getFloat(key, defValue)
    }

    /* get and put long value */
    fun setValue(key: String, value: Long) {
        mSharePre.edit().putLong(key, value).apply()
    }

    fun getValue(key: String, defValue: Long): Long {
        return mSharePre.getLong(key, defValue)
    }

    /* get and put string set value */
    fun setValue(key: String, value: Set<String>) {
        mSharePre.edit().putStringSet(key, value).apply()
    }

    fun getValue(key: String, defValue: Set<String>): Set<String>? {
        return mSharePre.getStringSet(key, defValue)
    }

    /* 添加和移除sp改变的监听 */
    fun registerSpChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
        mSharePre.registerOnSharedPreferenceChangeListener(listener)
    }

    fun unregisterSpChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
        mSharePre.unregisterOnSharedPreferenceChangeListener(listener)
    }

}